package com.pw.study.flink.state;

import com.pw.study.flink.entities.WaterSensor;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

public class KeyStateMap {

    public static void main(String[] args) {
        stateList();
    }

    private static void stateList() {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        //输入数据
        SingleOutputStreamOperator<WaterSensor> stream = env.socketTextStream("hadoop111", 9999).map(value -> {
            String[] line = value.split(",");
            return new WaterSensor(line[0], Long.valueOf(line[1]), Integer.valueOf(line[2]));
        });

        //处理数据
        stream.keyBy(WaterSensor::getId)
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    private MapState<Integer, Object> mapState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        mapState = getRuntimeContext().getMapState(new MapStateDescriptor<Integer, Object>("mapState", Integer.class, Object.class));
                    }

                    @Override
                    public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                        mapState.put(value.getVc(),new Object());
                        System.out.println("Values: "+mapState.values().toString());

                        List<Integer> list = StreamSupport.stream(mapState.keys().spliterator(), true).collect(Collectors.toList());
                        out.collect(ctx.getCurrentKey()+" 不重复的水位值 "+list);
                    }
                }).print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
